package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.backend.DTO.ProductDisplay;
import com.example.backend.DTO.listProduct;
import com.example.backend.entity.OrderInfo;
import com.example.backend.entity.ProductListing;
import com.example.backend.mapper.OrderInfoMapper;
import com.example.backend.mapper.ProductListingMapper;
import com.example.backend.util.AuthUtil;
import com.example.backend.mapper.AccountMapper;
import com.example.backend.service.BuyerService;
import com.example.backend.util.WeBASEUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private WeBASEUtils weBASEUtils;

    @Autowired
    private AuthUtil authUtil;
    
    @Autowired
    protected AccountMapper accountMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ProductListingMapper productListingMapper;

    @Override
    public String register(String username, String passWordF, String passwordS, String qualificationContent, int accountType) {
        return authUtil.register(username, passWordF, passwordS, qualificationContent, accountType);
    }
    
    @Override
    public String login(String accountId, String password, int accountType) {
        return authUtil.login(accountId, password, accountType);
    }
    
    @Override
    public String changePassword(String accountId, String oldPassword, String newPassword, int accountType) {
        return authUtil.changePassword(accountId, oldPassword, newPassword, accountType);
    }
    
    @Override
    public String postQualificationContent(String accountId, String qualificationContent, int accountType) {
        return authUtil.postQualificationContent(accountId, qualificationContent, accountType);
    }
    //下单
    //买家方要提供：交易单号，商品名称，商品数量，商品单价，商品总金额（在后端中计算）卖家账号，买家账号，交易状态，收货地址，交易方式，成交时间
    @Override
    public String placeOrder(Map<String,String> credentials) {
        if (credentials.get("productName") == null||credentials.get("quantity") == null||
                credentials.get("unit_price") == null||credentials.get("sellerId") == null||
                credentials.get("buyerId") == null|| credentials.get("order_status")==null||
                credentials.get("shipping_address") == null){
            return "参数不足或参数错误";
        }

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTransactionId(authUtil.generateOrderId());
        orderInfo.setProductName(credentials.get("productName"));
        orderInfo.setQuantity(Integer.valueOf(credentials.get("quantity")));
        orderInfo.setUnitPrice(new BigDecimal(credentials.get("unit_price")));
        orderInfo.setTotalAmount(new BigDecimal(orderInfo.getQuantity()).multiply(orderInfo.getUnitPrice()));
        orderInfo.setSellerId(credentials.get("sellerId"));
        orderInfo.setOrderStatus(credentials.get("order_status"));
        orderInfo.setBuyerId(credentials.get("buyerId"));
        orderInfo.setShippingAddress(credentials.get("shipping_address"));
        orderInfo.setDealTime(LocalDateTime.now());
        orderInfoMapper.insert(orderInfo);

        return "下单成功";
    }

    //获取已上架商品列表
    @Override
    public List<ProductListing> getAvailableProducts() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("listing_status",1);
        return productListingMapper.selectList(queryWrapper);
    }
    //获取已下单的商品列表
    @Override
    public List<listProduct> getPlacedProducts(Map<String,String> credentials) {
        //根据买家id进行多表查询，满足listProduct的内容
        String buyerId = credentials.get("buyerId");
        if (buyerId == null) {
            return new ArrayList<>();
        }
        
        // 1. 根据买家ID查询所有订单
        QueryWrapper<OrderInfo> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("buyer_id", buyerId);
        List<OrderInfo> orderList = orderInfoMapper.selectList(orderQueryWrapper);
        
        List<listProduct> productList = new ArrayList<>();
        
        // 2. 遍历订单，查询对应的商品信息并构建listProduct对象
        for (OrderInfo order : orderList) {
            // 根据商品名称查询商品信息
            QueryWrapper<ProductListing> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("product_name", order.getProductName());
            ProductListing product = productListingMapper.selectOne(productQueryWrapper);
            
            if (product != null) {
                listProduct listProductItem = new listProduct();
                // 设置订单相关信息
                listProductItem.setTransactionId(order.getTransactionId());
                listProductItem.setProductName(order.getProductName());
                listProductItem.setUnitPrice(order.getUnitPrice());
                listProductItem.setQuantity(order.getQuantity());
                listProductItem.setTotalAmount(order.getTotalAmount());
                listProductItem.setSellerId(order.getSellerId());
                listProductItem.setShippingAddress(order.getShippingAddress());
                listProductItem.setOrderStatus(order.getOrderStatus());
                
                // 设置商品相关信息
                listProductItem.setProductDescription(product.getProductDescription());
                
                // 处理商品图片
                listProductItem.setProductImages(product.getProductImages());
                
                productList.add(listProductItem);
            }
        }
        
        return productList;
    }

    //确认收货
    @Override
    public String confirmReceipt(String transactionId, String buyerId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("transaction_id", transactionId);
        queryWrapper.eq("buyer_id", buyerId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo == null) {
            return "单号或买家id错误";
        }
        // 更新订单状态为已收货completed
        orderInfo.setOrderStatus("completed");
        orderInfo.setConfirmReceiptTime(LocalDateTime.now());
        orderInfoMapper.update(orderInfo, queryWrapper);
        //数据上链(交易单号、账号、状态（确认收货）、确认时间戳)
        try {
            //数据上链(交易单号、账号、状态（取消订单）、时间戳)
            List<Object> param = new ArrayList<>();
            param.add(transactionId);
            param.add(buyerId);
            param.add("completed");
            weBASEUtils.funcPost("ReceiptModule","confirmReceipt",param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return "确认收货成功";
        }



    }
    //支付
    @Override
    public String pay(String transactionId, String buyerId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("transaction_id", transactionId);
        queryWrapper.eq("buyer_id", buyerId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo == null) {
            return "单号或买家id错误";
        }
        // 更新订单状态为已支付
        orderInfo.setOrderStatus("paid");
        orderInfoMapper.update(orderInfo, queryWrapper);
        return "支付成功";

    }


    //退货
    @Override
    public String returnProduct (Map<String, String> credentials) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("transaction_id", credentials.get("transactionId"));
        queryWrapper.eq("buyer_id", credentials.get("buyerId"));
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo == null) {
            return "单号或买家id错误";
        }
        orderInfo.setOrderStatus("returned");
        orderInfoMapper.update(orderInfo, queryWrapper);
        //数据上链(交易单号、账号、状态（退货）、退货时间戳)
        try {
            //数据上链(交易单号、账号、状态（取消订单）、时间戳)
            List<Object> param = new ArrayList<>();
            param.add(credentials.get("transactionId"));
            param.add(credentials.get("buyerId"));
            param.add("returned");
            weBASEUtils.funcPost("ReceiptModule","confirmReceipt",param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return "退货成功";
        }


    }

    //取消订单
    @Override
    public String cancelOrder (Map<String , String> credentials){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("transaction_id", credentials.get("transactionId"));
        queryWrapper.eq("buyer_id", credentials.get("buyerId"));
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo == null) {
            return "单号或买家id错误";
        }
        orderInfo.setOrderStatus("cancelled");
        orderInfoMapper.update(orderInfo, queryWrapper);
        try {
            //数据上链(交易单号、账号、状态（取消订单）、时间戳)
            List<Object> param = new ArrayList<>();
            param.add(credentials.get("transactionId"));
            param.add(credentials.get("buyerId"));
            param.add("cancelled");
            weBASEUtils.funcPost("ReceiptModule","confirmReceipt",param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return "取消订单成功";
        }
    }

}